package crontab

import (
	"github.com/spf13/cast"
	global2 "longmen/server/config/global"
	imsdk2 "longmen/server/internal/rpc/tencentim/imsdk"
	"longmen/server/pkg/db/mysql/models/models_main"
	"longmen/server/pkg/db/redis/cache"
)

func CreateImRoom() {
	var anchor []int64

	//	取得主播列表
	err := global2.GetX().Model(&models_main.User{}).Select("id as anchor").Where("is_anchor = 1 and id > 269450").Scan(&anchor).Error
	if err != nil {
		global2.Log.Errorf("get anchor error:%s", err.Error())
		return
	}
	global2.Log.Debugf("anchor:%+v", anchor)
	cacheKey := "createImRoom"
	var alreadyCreateImRoomIds []int64
	cache.GetCachedData(cacheKey, &alreadyCreateImRoomIds)
	var anchorIds []int64
	for _, v := range anchor {
		found := false
		for _, id := range alreadyCreateImRoomIds {
			if v == id {
				found = true
				break
			}
		}
		if found {
			continue
		}
		// 開立帳號
		a := cast.ToString(v)
		acc := imsdk2.CreateAccountRequest{
			UserID: a,
			Nick:   a,
		}
		imsdk2.GetSdk().CreateAccount(acc)

		// 開立房間
		r := imsdk2.CreateGroupRequest{
			OwnerAccount: a,
			GroupID:      a,
			Name:         a,
		}
		if imsdk2.GetSdk().CreateGroup(r) {
			anchorIds = append(anchorIds, v)
		}
	}
	if len(anchorIds) > 0 {
		if len(alreadyCreateImRoomIds) > 0 {
			anchorIds = append(anchorIds, alreadyCreateImRoomIds...)
		}
		cache.SetCacheData(cacheKey, anchorIds, 0)
	}
}
func CreateOneRoom(a string) {
	acc := imsdk2.CreateAccountRequest{
		UserID: a,
		Nick:   a,
	}
	imsdk2.GetSdk().CreateAccount(acc)

	// 開立房間
	r := imsdk2.CreateGroupRequest{
		OwnerAccount: a,
		GroupID:      a,
		Name:         a,
	}
	if imsdk2.GetSdk().CreateGroup(r) {
		global2.Log.Infof("open group ok:%d", a)
	} else {
		global2.Log.Infof("open group failed:%d", a)
	}
}

func CreateOneFansGroup(groupId, name string) {
	r := imsdk2.CreateFansGroupRequest{
		OwnerAccount: "admin", // 群管理员
		GroupID:      groupId, // 群ID，需要生成规则并保存到表里
		Name: func() string {
			r := []rune(name)
			if len(r) > 10 {
				r = r[:10]
			}
			return string(r)
		}(), // 群名称
	}

	if imsdk2.GetSdk().CreateFansGroup(r) {
		global2.Log.Infof("open group ok:%v", groupId)
	} else {
		global2.Log.Infof("open group failed:%d", groupId)
	}
}
